import { userService } from '@/services/test-services';
import type { draggableAPI } from './models';
import type { Effect, Reducer, Subscription } from '@umijs/max';
import { generateId } from '@/util/utils';

const { queryUserDataList } = userService;

const iD1 = generateId();
const iD2 = generateId();
const iD3 = generateId();

export interface IndexModelType {
  namespace: 'draggableModel';
  state: draggableAPI.IState;
  effects: {
    queryUserDataList: Effect;
  };
  reducers: {
    save: Reducer<draggableAPI.IState>;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'draggableModel',

  state: {
    leftLists: [
      {
        id: 'apple',
        content: 'apple',
      },
      {
        id: 'watermelon',
        content: 'watermelon',
      },
      {
        id: 'banana',
        content: 'banana',
      },
      {
        id: 'lemon',
        content: 'lemon',
      },
      {
        id: 'orange',
        content: 'orange',
      },
      {
        id: 'grape',
        content: 'grape',
      },
    ],
    moduleFloorList: [
      {
        id: iD1,
        moduleList: [
          {
            id: 'strawberry1',
            content: 'strawberry 1',
          },
          {
            id: 'cherry1',
            content: 'cherry 1',
          },
        ],
      },
      {
        id: iD2,
        moduleList: [
          {
            id: 'strawberry2',
            content: 'strawberry 2',
          },
          {
            id: 'cherry2',
            content: 'cherry 2',
          },
        ],
      },
      {
        id: iD3,
        moduleList: [
          {
            id: 'strawberry3',
            content: 'strawberry 3',
          },
          {
            id: 'cherry3',
            content: 'cherry 3',
          },
        ],
      },
    ],
  },

  effects: {
    *queryUserDataList({}, { call }): any {
      const response = yield call(queryUserDataList, {});
      console.log('userList', response);
      try {
        if (response.success) {
          // yield put({
          //   type: 'save',
          //   payload: {
          //     userList,
          //   },
          // });
        }
      } catch (error) {
        console.error(error);
      }
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    setup({ history }) {
      return history.listen((listener) => {
        const { location } = listener;
        if (location.pathname.includes('/draggable')) {
          // dispatch({
          //   type: 'queryUserDataList',
          // });
        }
      });
    },
  },
};

export default IndexModel;
